package code.class3;

import common.ArrayUtils;

/**
 * 双指针算法
 * <p>
 * https://leetcode.cn/problems/sort-array-by-parity-ii/description/
 * 按奇偶排序数组ii
 * 移动奇偶数，将奇数位放奇数，偶数位放偶数
 * [3,5,4,6,2,7,4,9]
 */
public class Code01_doublePointer {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        arr = sortArrayByParity(arr);
        ArrayUtils.printArr(arr);
    }

    /**
     *
     */
    public static int[] sortArrayByParity(int[] arr) {
        // e是偶数位置 0, o是奇数位 1
        int e = 0, o = 1, n = arr.length - 1;
        while (e < arr.length && o < arr.length) {
            if ((arr[n] & 1) == 0) {
                swap(arr, e, n);
                e += 2;
            } else {
                swap(arr, o, n);
                o += 2;
            }
        }
        return arr;
    }

    public static void swap(int[] arr, int x, int y) {
        int t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
}
